﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Documents;
using System.Diagnostics;

namespace ViewMaker.Core.Wpf
{
    public static class RequestNavigateBehavior
    {
        public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached("IsEnabled", typeof(bool), typeof(RequestNavigateBehavior), new PropertyMetadata(IsEnabledCallback));

        public static bool GetIsEnabled(Hyperlink obj)
        {
            return (bool)obj.GetValue(IsEnabledProperty);
        }

        public static void SetIsEnabled(Hyperlink obj, bool value)
        {
            obj.SetValue(IsEnabledProperty, value);
        }

        private static void IsEnabledCallback(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            var ele = obj as Hyperlink;
            if (ele != null)
            {
                if ((bool)args.OldValue)
                {
                    ele.RequestNavigate -= new System.Windows.Navigation.RequestNavigateEventHandler(RequestNavigateHandler);
                }
                if ((bool)args.NewValue)
                {
                    ele.RequestNavigate += new System.Windows.Navigation.RequestNavigateEventHandler(RequestNavigateHandler);
                }
            }
        }

        static void RequestNavigateHandler(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
        {
            var ele = e.OriginalSource as Hyperlink;
            Process.Start(e.Uri.AbsoluteUri);
            e.Handled = true;
        }
    }

}
